﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using DataAccess;
using Model.EntityModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for RemissionOfCase.xaml
    /// </summary>
    public partial class RemissionOfCaseUI : UserControl
    {
        public long ComplaintId { get; set; }
        public bool WasPrinted { get; set; }
        public bool WasSaved { get; set; }
        public RemissionOfCase RemissionOfCurrentCase { get; set; }

        public RemissionOfCaseUI(long complaintId)
        {
            ComplaintId = complaintId;
            RemissionOfCurrentCase = ComplaintDataAccess.GetRemissionOfCase(ComplaintId);
            InitializeComponent();
            this.Unloaded += ExitingRemission;
            if (RemissionOfCurrentCase == null)
            {
                lblRemissionDate.Content = DateTime.Now.ToShortDateString();
                lblCaseNumber.Content = complaintId;
                lblCaseNum.Content = complaintId;
                tbRemitedPeople.AddValitationRule(new LenghtValidationRule(5));
                tbMrOrMs.AddValitationRule(new LenghtValidationRule(3));
                btnPrint.Visibility = Visibility.Hidden;
                btnSave.Visibility = Visibility.Visible;
            }
            else SetRemissionOfCase();
            var complaint = ComplaintDataAccess.GetComplaintById(complaintId);
            Actor complainant = new Actor();
            Actor aggressor = new Actor();
            foreach (var actor in complaint.Actor)
            {
                if (actor.Type == "Denunciante")
                    complainant = actor;
                if (actor.Type == "Agresor")
                    aggressor = actor;
            }
            lblComplainantName.Content = complainant.Person.Name + " " + complainant.Person.PaternalName + " " +
                                         complainant.Person.MaternalName;
            lblComplainantCi.Content = complainant.Person.CiPassport;

            lblAggressorName.Content = aggressor.Person.Name + " " + aggressor.Person.PaternalName + " " +
                                       aggressor.Person.MaternalName;
            lblAggressorCi.Content = aggressor.Person.CiPassport;
            var employees = ComplaintDataAccess.GetAllEmployeeOfComplaintFromComp(ComplaintId);
            foreach (var employeeOfComplaint in employees)
            {
                if (employeeOfComplaint.Responsability == "Asignada")
                    lblAsignedName.Content = employeeOfComplaint.Employee.Name + " " +
                                             employeeOfComplaint.Employee.PaternalName + " " +
                                             employeeOfComplaint.Employee.MaternalName;
            }
            
        }

        private void SetRemissionOfCase()
        {
            Xceed.Wpf.Toolkit.MessageBox.Show("Este caso ya fué remitido!, podrá ver e imprimir la información, pero no cambiarla",
                                              "Información", MessageBoxButton.OK, MessageBoxImage.Information);
            lblCaseNumber.Content = RemissionOfCurrentCase.ComplaintId;
            lblCaseNum.Content = RemissionOfCurrentCase.ComplaintId;
            lblRemissionDate.Content = RemissionOfCurrentCase.RemisionDate.ToShortDateString();
            tbRemitedPeople.Text = RemissionOfCurrentCase.RemmitedPersons;
            tbRemitedPeople.IsReadOnly = true;
            tbMrOrMs.Text = RemissionOfCurrentCase.IntendedForMrOrMrs;
            tbMrOrMs.IsReadOnly = true;
            tbInstitution.Text = RemissionOfCurrentCase.Institution;
            tbInstitution.IsReadOnly = true;
            tbFojasNumber.Text = RemissionOfCurrentCase.FoliosNumber.ToString();
            tbFojasNumber.IsReadOnly = true;
            tbImpedimentDays.Text = RemissionOfCurrentCase.ImpedimentDays.ToString();
            btnSave.Visibility = Visibility.Hidden;
            lblMrOrMs.Content = RemissionOfCurrentCase.IntendedForMrOrMrs;
            WasSaved = true;
            btnPrint.Visibility = Visibility.Visible;
        }

        private void ExitingRemission(object sender, RoutedEventArgs e)
        {
            if (WasPrinted && !WasSaved)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(
                    "Usted imprimió la remision de caso, pero no la guardó, la remision de caso se debe guardar!",
                    "Informacion!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                btnSave_Click(btnSave, null);
            }

        }

        private void tbMrOrMs_TextChanged(object sender, TextChangedEventArgs e)
        {
            lblMrOrMs.Content = tbMrOrMs.Text;
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            var items = new ObservableCollection<UserControl>();
            items.Add(new PrintRemissionOfCase(ComplaintId));
            var a = new PrintPreviewDialogV2(items);
            a.MenuItem_Click(null, null);
        }


        private bool CheckHasErrors()
        {
            tbMrOrMs.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            tbRemitedPeople.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            tbFojasNumber.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            tbImpedimentDays.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            tbInstitution.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            return Validation.GetHasError(tbMrOrMs) || Validation.GetHasError(tbRemitedPeople) ||
                   Validation.GetHasError(tbFojasNumber) || Validation.GetHasError(tbImpedimentDays) ||
                   Validation.GetHasError(tbInstitution);
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckHasErrors())
            {
                MessageBoxResult res = MessageBoxResult.Yes;
                if (!WasPrinted && !WasSaved)
                {
                    var style = new Style(typeof (Xceed.Wpf.Toolkit.MessageBox));
                    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
                    res = Xceed.Wpf.Toolkit.MessageBox.Show("Esta seguro(a) de que desea remitir el caso?",
                                                                "Confirmar Accion!", MessageBoxButton.YesNo,
                                                                MessageBoxImage.Warning, style);
                }
                if (res == MessageBoxResult.Yes)
                {
                    var style = new Style(typeof(Xceed.Wpf.Toolkit.MessageBox));
                    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
                    RemissionOfCase remissionOfCase = new RemissionOfCase();
                    remissionOfCase.ComplaintId = ComplaintId;
                    remissionOfCase.FoliosNumber = int.Parse(tbFojasNumber.Text);
                    remissionOfCase.ImpedimentDays = int.Parse(tbImpedimentDays.Text);
                    remissionOfCase.RemisionDate = DateTime.Parse(lblRemissionDate.Content as string);
                    remissionOfCase.Institution = tbInstitution.Text;
                    remissionOfCase.IntendedForMrOrMrs = tbMrOrMs.Text;
                    remissionOfCase.RemmitedPersons = tbRemitedPeople.Text;
                    ComplaintDataAccess.InsertRemmissionOfCase(remissionOfCase);
                    res = Xceed.Wpf.Toolkit.MessageBox.Show("Se guardó la remision de caso exitosamente! desea imprimir la remisión de caso?",
                                                                "Exito!", MessageBoxButton.YesNo,
                                                                MessageBoxImage.Information, style);
                    if (res== MessageBoxResult.Yes)
                    {
                        PrintPreview_Click(null, null);
                    }
                    else
                    {
                        Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la remisión de caso posteriormente, entrando nuevamente a la opcion de remisión de caso",
                                                                "Información!", MessageBoxButton.OK,                                           MessageBoxImage.Information);
                    }
                    WasSaved = true;
                    if(this.Parent!=null)
                        UIWindowManager.CleanWindow(this);
                }
            }
            else
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(
                        "No puede guardar la Remision de caso hasta haber completado todos los campos!",
                        "Información", MessageBoxButton.OK, MessageBoxImage.Information);
               
            }
        }

        private void PrintPreview_Click(object sender, RoutedEventArgs e)
        {
            var items = new ObservableCollection<UserControl>();
            items.Add(new PrintRemissionOfCase(ComplaintId));
            var a = new PrintPreviewDialogV2(items);
            a.ShowDialog();
        }

        private void btnPrint_Click_1(object sender, RoutedEventArgs e)
        {
            DrpDownPrintOptions.IsOpen = true;
        }
    }
}
